<?php
namespace api\modules\v1\models\feedback;

use api\modules\common\models\User;
use common\models\CacheKeys;
use common\models\Functions;
use common\models\Patterns;
use common\models\Status;
use common\services\upload\Qiniu;
use yii\base\Exception;
use Yii;
/**
 * This is the model class for table "goods".
 *
 * @property int $id
 * @property string $name
 */
class FeedbackInfo extends \common\models\feedback\FeedbackInfo
{
    public function rules()
    {
        return [
            [['summary','images','phone'],'required','message' => "{attribute}不能为空", 'on' => ['feedback']],
            [['summary'],'filter','filter' => 'trim','on' => ['feedback']],
            [['summary'],'string','min' => '0','max' => '200','message' => "{attribute}需要200字符以内",'on' => ['feedback']],
            ['images', 'validateImage', 'on' => ['feedback']],
            ['phone', 'validatePhone', 'on' => ['feedback']],
        ];
    }

    public function attributeLabels()
    {
        return [
            'summary' => '描述',
            'images' => '图片',
            'phone' => '联系方式',
        ];
    }

    /**
     * 设置场景
     * @return array
     */
    public function scenarios()
    {
        $scenarios = [
            'feedback' => [
                'summary',
                'images',
                'phone',
            ],
        ];
        return array_merge(parent::scenarios(), $scenarios);
    }

    // 验证图片数量
    public function validateImage($attribute) {
        if (!$this->hasErrors()) {
            $config = static::getCommonByKey(['feedback_image_num','feedback_everyday_num']);
            if (count($this->images) > $config['feedback_image_num']) {
                $this->addError($attribute, "反馈截图最多{$config['feedback_image_num']}张");
            }
        }
    }

    // 验证联系方式
    public function validatePhone($attribute) {
        if (!$this->hasErrors()) {
            if (!preg_match(Patterns::matchEmail(), $this->phone) && !preg_match(Patterns::phoneNumber(), $this->phone)) {
                $this->addError($attribute, "请输入正确的邮箱或者手机号");
            }
        }
    }

    // 反馈操作
    public function saveInfo() {
        $redis = Yii::$app->redis;
        $user = Yii::$app->getUser()->getIdentity()->toArray();
        try {
            if (!$this->validate()) {
                throw new Exception($this->getErrorSummary(true)[0]);
            }

            CacheKeys::checkFrequency($user['id'],1);
            $exists = $redis->get("FEEDBACK" . $user['id']);
            if($exists){
                throw new Exception('您的速度太快了！');
            }

             // 是否实名
             if ($user['is_kyc'] != Status::COMMON_RADIO_YES) {
                throw new Exception('请先实名认证');
            }
            
            $post = Yii::$app->request->post();
            $data = [];
            $data = array_merge($data, $this->getSaveData($this->scenario, $post));


            $config = static::getCommonByKey(['feedback_everyday_num']);
            $checkUserCount = static::getCountByWhere(['user_id' => $user['id']]);
            if (($checkUserCount + 1) > $config['feedback_everyday_num']) {
                throw new Exception("每天最多反馈{$config['feedback_everyday_num']}次");
            }

            $data["user_id"] = $user['id'];
            $data["images"] = json_encode($this->images);
            $data["create_time"] = date("Y-m-d H:i:s");

            $res = static::insertData($data);
            if ($res === false) {
                throw new Exception('系统异常，请稍后再试');
            }

            return Functions::formatRestAPI(0, '感谢您的反馈，我们会尽快核实处理！');
        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '服务异常');
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        } finally {
            $redis->del("FEEDBACK" .  $user['id']);
        }
    }

    public function getList() {
        try {
            $get = \Yii::$app->request->get();
            $page = $get['page'] ?? 1;
            $size = $get['size'] ?? 10;
            $where = [];
            if (!empty($get['status'])) {
                $where['status'] = $get['status'];
            }
            $count = static::getCountByWhere($where);

            $data = static::setPageinationAPI($page, $size, $count);

            $offset = ($page - 1) * $size;

            $list = static::getByWhere($where, ["*"], "create_time DESC", $offset, $size);

            $result = [];

            foreach ($list as $v) {
                $tmp = [
                    "time" => strtotime($v['create_time']),
                    "status" => $v['status'],
                    "status_name" => $v['status'] == Status::COMMON_RADIO_YES ? "处理中" : "已完成",
                    "summary" => $v['summary'],
                    "assets" =>  static::getAllImages($v['images']),
                    "type" => $v['feedback_type'],
                    "phone" => $v['phone'],
                    "reply_info" => null
                ];

                if (!empty($v['reply'])) {
                    $tmp['reply_info'] = [
                        'message' => $v['reply'],
                        'time' => strtotime($v['reply_time']),
                    ];
                }
                $result[] = $tmp;
            }

            $data['data'] = $result;

            return Functions::formatRestAPI(0, '', $data);
        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '服务异常');
        } catch (Exception $e) {
            return Functions::formatRestAPI(0, $e->getMessage());
        }
    }
}
